<?php

namespace app\index\controller;

use ModbusMaster;

class Modbus
{

    // ThinPHP5.1
    public function index()
    {
        // Modbus master UDP
        $modbus = new ModbusMaster("127.0.0.1", "TCP");
        // Read multiple registers
        try {
            $recData = $modbus->readMultipleRegisters(0, 0, 5);
        }
        catch (Exception $e) {
            var_dump($e->getMessage());die;
            // Print error information if any
            echo $modbus;
            echo $e;
            exit;
        }

        // 数据库设备的数据描述
        $devicesDataBlock = [
            "0" => "weather",
            "1" => "water",
            "2" => "voice",
            "3" => "electric",
            "4" => "air"
        ];

        $realData = [];

        foreach($recData as $key => $value) {
            $indexs = ($key-1)/2;
            if (($key-1)%2 == 0) {
                $realData[$devicesDataBlock[$indexs]] = $value;
            }
        }

        // --存入数据库部分
        // ##此处是代码
        // --存入数据库部分

        var_dump($realData);die;

        // Print data in string format
        echo PhpType::bytes2string($recData);

    }



}
